import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { customers } from '@/lib/schema';
import { eq } from 'drizzle-orm';

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const customer = await db
      .select()
      .from(customers)
      .where(eq(customers.id, parseInt(params.id)))
      .limit(1);

    if (customer.length === 0) {
      return NextResponse.json(
        { error: '客户不存在' },
        { status: 404 }
      );
    }

    return NextResponse.json(customer[0]);
  } catch (error) {
    console.error('获取客户详情失败:', error);
    return NextResponse.json(
      { error: '获取客户详情失败' },
      { status: 500 }
    );
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const body = await request.json();
    
    const [updatedCustomer] = await db
      .update(customers)
      .set({
        name: body.name,
        email: body.email,
        phone: body.phone,
        phone2: body.phone2,
        phone2Purpose: body.phone2Purpose,
        wechat: body.wechat,
        wechatPurpose: body.wechatPurpose,
        qq: body.qq,
        qqPurpose: body.qqPurpose,
        whatsapp: body.whatsapp,
        whatsappPurpose: body.whatsappPurpose,
        telegram: body.telegram,
        telegramPurpose: body.telegramPurpose,
        address: body.address,
      })
      .where(eq(customers.id, parseInt(params.id)))
      .returning();

    return NextResponse.json(updatedCustomer);
  } catch (error: any) {
    console.error('更新客户失败:', error);
    
    if (error.message?.includes('UNIQUE constraint failed')) {
      return NextResponse.json(
        { error: '邮箱已存在，请使用其他邮箱地址' },
        { status: 400 }
      );
    }
    
    return NextResponse.json(
      { error: '更新客户失败: ' + (error.message || '数据库错误') },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    await db
      .delete(customers)
      .where(eq(customers.id, parseInt(params.id)));

    return NextResponse.json({ message: '客户删除成功' });
  } catch (error: any) {
    console.error('删除客户失败:', error);
    return NextResponse.json(
      { error: '删除客户失败: ' + (error.message || '数据库错误') },
      { status: 500 }
    );
  }
}